import pandas as pd
import numpy as np
from PyQt6.QtCore import QObject, pyqtSignal
from pathlib import Path
import logging


class DataModel(QObject):
	# 自定义信号
	data_loaded = pyqtSignal(pd.DataFrame)
	analysis_error = pyqtSignal(str)
	
	@staticmethod
	def load_file(file_path: str, chunk_size=5000) -> pd.DataFrame:
		"""安全加载Excel文件（支持大文件分块读取）"""
		try:
			# 使用openpyxl引擎优化读取性能
			reader = pd.read_excel(
				file_path
			)
			chunks = []
			for chunk in reader:
				# 类型转换优化
				chunk = chunk.apply(
					lambda x: pd.to_numeric(x, errors='ignore')
					if x.dtype == object
					else x
				)
				chunks.append(chunk)
			
			df = pd.concat(chunks, ignore_index=True)
			logging.info(f"成功加载文件: {Path(file_path).name}")
			return df
		except Exception as e:
			logging.error(f"文件加载失败: {str(e)}")
			raise ValueError(f"文件读取错误: {str(e)}")
	
	@staticmethod
	def analyze(df: pd.DataFrame) -> dict:
		"""执行基础数据分析"""
		try:
			# 自动检测时间序列
			time_col = next((col for col in df.columns
			                 if 'date' in col.lower()), None)
			
			# 数值型列分析
			numeric_cols = df.select_dtypes(include=np.number).columns
			stats = {
				'mean': df[numeric_cols].mean().to_dict(),
				'max': df[numeric_cols].max().to_dict(),
				'min': df[numeric_cols].min().to_dict()
			}
			
			# 生成默认图表数据
			chart_data = {
				'x': df[time_col].values if time_col else df.index.values,
				'y': df[numeric_cols[0]].values if len(numeric_cols) > 0 else [],
				'stats': stats,
				'columns': list(df.columns)
			}
			return chart_data
		except Exception as e:
			logging.error(f"数据分析失败: {str(e)}")
			raise RuntimeError(f"分析错误: {str(e)}")
	
	@classmethod
	def create_chart(cls, data: dict) -> dict:
		"""生成标准化图表数据结构"""
		return {
			'title': f"分析图表 - {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M')}",
			'type': 'line',  # 可扩展为bar/pie等
			'data': {
				'labels': data['x'].tolist(),
				'datasets': [{
					'label': '数值',
					'data': data['y'].tolist(),
					'borderColor': '#487eb0',
					'fill': False
				}]
			},
			'stats': data.get('stats', {})
		}
